package com.gis.servlet.find;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.gis.bean.Point;
import com.gis.dao.FindDao;
import com.gis.dto.FindDto;
import com.gis.util.GisUtil;
import com.gis.util.ResponseUtil;
import com.gis.util.RestResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author t-zhaoheng
 * @since 2022/5/16
 */
@WebServlet("/find/all")
public class FindAllServlet extends HttpServlet {
  FindDao findDao = FindDao.getInstance();

  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    doPost(req, resp);
  }

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    Map<String, Object> params = new HashMap<>();
    String goodsTypeId = req.getParameter("goodsTypeId");
    if (StrUtil.isNotBlank(goodsTypeId)) {
      params.put("goodsTypeId", goodsTypeId);
    }
    String startDate = req.getParameter("startDate");
    if (StrUtil.isNotBlank(startDate)) {
      params.put("startDate", startDate);
    }
    String endDate = req.getParameter("endDate");
    if(StrUtil.isNotBlank(endDate)) {
      params.put("endDate", endDate);
    }
    String points = req.getParameter("points");
    List<Point> pointList = new ArrayList<>();
    List<Double> lonList = new ArrayList<>();
    List<Double> latList = new ArrayList<>();
    if(StrUtil.isNotBlank(points)) {
      pointList = JSONArray.parseArray(points, Point.class);
    }
    for (Point point : pointList) {
      lonList.add(point.getLng());
      latList.add(point.getLat());
    }
    Double[] lons = Convert.toDoubleArray(lonList);
    Double[] lats = Convert.toDoubleArray(latList);


    // 查询出所有的失物招领
    List<FindDto> findDtoList = findDao.listAll(params);

    if(CollectionUtil.isNotEmpty(pointList)) {
      findDtoList = findDtoList.stream().filter(findDto -> {
        // 保证返回的经纬度位于选取的点中
        Double lng = findDto.getLng();
        Double lat = findDto.getLat();

        boolean b = GisUtil.isInPolygon(lng, lat, lons, lats);
        return b;
      }).collect(Collectors.toList());
    }

    ResponseUtil.writeJson(resp, RestResponse.success(findDtoList));
  }
}
